<!--
 * @Description: VPN列表
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-10-13 09:41:15
 * @LastEditTime: 2021-11-15 22:16:23
 * @LastEditors: 0001101008/HuYuxi
-->
<template>
  <div class="page-content">
    <table-bar :showTop="false" :columns="columns" @changeColumn="changeColumn">
      <div slot="top">
        <el-form :model="filterSearch" label-width="70px" label-position="left">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <!-- VPN名称 -->
              <el-form-item label="VPN名称">
                <el-input v-model.trim="filterSearch.userlabel" placeholder="请输入VPN名称"></el-input>
              </el-form-item>
            </el-col>
            <!-- 搜索 重置 -->
            <el-row :xs="24" :sm="12" :lg="6" style="float: right; margin-right: 10px;">
              <el-button type="primary" @click="search">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
      <div slot="bottom">
        <!-- 新建 -->
        <el-button size="medium" type="primary" plain @click="showDialog('add')" v-power="2">新建</el-button>
      </div>
    </table-bar>
    <tao-table
      class="table-box"
      :data="dataList"
      :page="page"
      @changePage="changePage"
      :showPage="true"
      ref="table"
    >
      <!-- 详情 -->
      <el-table-column align="center" width="80" label="详情" type="expand">
        <template slot-scope="scope">
          <info :sites="scope.row.vpnList" />
        </template>
      </el-table-column>
      <!-- ID -->
      <el-table-column
        v-if="columns[0].show"
        align="center"
        width="100"
        label="ID"
        sortable
        prop="id"
      />
      <!-- 租户 -->
      <el-table-column
        v-if="columns[1].show"
        align="center"
        width="200"
        label="租户"
        show-overflow-tooltip
        prop="dgName"
      />
      <!-- 实例名称 -->
      <el-table-column
        v-if="columns[2].show"
        align="center"
        label="实例名称"
        width="150"
        prop="instanceName"
        show-overflow-tooltip
      />
      <!-- VPN -->
      <el-table-column
        v-if="columns[3].show"
        align="center"
        label="VPN"
        width="150"
        prop="userlabel"
        show-overflow-tooltip
      />
      <!-- RD -->
      <el-table-column
        v-if="columns[4].show"
        align="center"
        label="RD"
        width="150"
        prop="rd"
        show-overflow-tooltip
      />
      <!-- 描述 -->
      <el-table-column
        v-if="columns[5].show"
        min-width="150"
        label="描述"
        show-overflow-tooltip
        prop="description"
      />
      <!-- 状态 -->
      <el-table-column v-if="columns[4].show" align="center" width="120" label="状态" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-power="scope.row.dgId === 100000 ? 0 : 2"
            v-model="scope.row.status"
            @change="statusSwitch(scope.row)"
          ></el-switch>
          {{scope.row.status ? '启用' : '停用'}}
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column fixed="right" label="操作" align="center" width="160px">
        <!--  删除-->
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="showDialog('edit', scope.row)"
            v-power="scope.row.dgId === 100000 ? 0 : 2"
          >编辑</el-button>
          <el-button
            type="text"
            style="color: #FA6962"
            icon="el-icon-delete"
            @click="handleDelete(scope)"
            v-power="scope.row.dgId === 100000 ? 0 : 2"
          >删除</el-button>
        </template>
      </el-table-column>
    </tao-table>
    <!-- 弹出框 -->
    <el-dialog
      :title="diagTitle"
      :close-on-click-modal="false"
      width="500px"
      :visible.sync="dvEdit"
    >
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
        <!-- 租户 -->
        <el-form-item label="租户" prop="dgId">
          <el-select
            class="order-cover-select"
            v-model="form.dgId"
            clearable
            @clear="filterVmModel"
            placeholder="请选择租户"
            filterable
            v-el-select-loadmore="loadmore"
            :filter-method="filterVmModel"
            style="width: 100%;"
            :disabled="form.id ? true: false"
          >
            <el-option
              v-for="item in tenants"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 实例名称 -->
        <el-form-item label="实例名称" prop="instanceName">
          <el-input
            v-model="form.instanceName"
            maxlength="32"
            placeholder="请填写实例名称"
            :disabled="form.id ? true: false"
          ></el-input>
        </el-form-item>
        <!-- VPN -->
        <el-form-item label="VPN" prop="userlabel">
          <el-input v-model="form.userlabel" maxlength="50" placeholder="请填写VPN名称"></el-input>
        </el-form-item>
        <!-- RD -->
        <el-form-item label="RD" prop="rd">
          <el-input
            v-model="form.rd"
            maxlength="16"
            placeholder="0:65535"
            :disabled="form.id ? true: false"
          ></el-input>
        </el-form-item>
        <!-- 站点选择 -->
        <el-form-item
          label="站点选择"
          prop="siteIdList"
          :rules="{ required: false, message: '请选择站点', trigger: 'change' }"
          v-show="siteFlag"
        >
          <el-select v-model="form.siteIdList" multiple collapse-tags style="width: 100%;">
            <el-option
              v-for="item in siteList"
              :key="item.id"
              :label="item.sitename"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 描述 -->
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="3"
            v-model="form.description"
            maxlength="200"
            show-word-limit
            placeholder="请填写VPN描述内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!--取 消  确 定-->
        <el-button @click="dvEdit = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import info from './info';
export default {
  components: {
    info
  },
  directives: {
    // 计算是否滚动到最下面
    'el-select-loadmore': {
      bind (el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          // scrollHeight 获取元素内容高度(只读)
          // scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
          // clientHeight 读取元素的可见高度(只读)
          // 如果元素滚动到底, 下面等式返回true, 没有则返回false:
          const condition = Math.round(this.scrollHeight - this.scrollTop) <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      }
    }
  },
  data () {
    return {
      dvEdit: false,
      dataList: [],
      filterSearch: {
        userlabel: null
      },
      page: {
        page: 1,
        pageSize: 15,
        total: 0
      },
      columns: [
        { name: 'ID', show: true },
        { name: '租户', show: true },
        { name: '实例名称', show: true },
        { name: 'VPN', show: true },
        { name: 'RD', show: true },
        { name: '描述', show: true },
        { name: '状态', show: true }
      ],
      // 租户集合
      tenants: [],
      // 筛选文本
      filterText: '',
      form: {
        id: null,
        dgId: null,
        instanceName: null,
        userlabel: null,
        rd: null,
        siteIdList: [],
        description: null
      },
      rules: {
        dgId: [{ required: true, type: 'number', message: '请选择租户', trigger: 'change' }],
        instanceName: [{
          required: true,
          message: '请填写实例名称',
          trigger: 'blur'
        }, {
          pattern: /^[A-Za-z0-9]+$/,
          message: '请输入字母或数字',
          trigger: 'blur'
        }],
        userlabel: [{ required: true, message: '请填写VPN名称', trigger: 'blur' }],
        rd: [{ required: true, message: '请填写RD', trigger: 'blur' }, { pattern: /^\d+:\d+$/, message: '格式不正确', trigger: 'blur' }],
        // siteIdList: [{ required: true, message: '请选择站点', trigger: 'change' }]
      },
      siteList: [],
      diagTitle: '新建租户VPN',
      siteFlag: true
    };
  },
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      _this.refresh();
      _this.popSites();
      _this.loadmore(true);
    });
  },
  methods: {
    // 获取所选租户的可用POP站点数据
    popSites () {
      let _this = this;
      _this.$http.get({
        url: '/api/sdwan/vpn/get/popSiteList/all'
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          for (let i = 0; i < resultBody.length; i++) {
            resultBody[i].disabled = false;
          }
          _this.siteList = resultBody;
        }
      });
    },
    // 状态开关
    statusSwitch (val) {
      let _this = this;
      let title = val.status ? '启用' : '停用';
      _this.$http.post({
        url: '/api/sdwan/vpn/config/vpn',
        data: {
          vpnId: val.id,
          status: title === '启用' ? 1 : 0
        }
      }).then(res => {
        let { status } = res;
        if (status === '0') {
          _this.$message.success(title + '成功！');
          _this.refresh();
        } else {
          _this.refresh();
        }
      }).catch(err => {
        _this.refresh();
      });
    },
    // 分页方法 详见 directives
    loadmore (firstTag) {
      let _this = this;
      // 筛选时下拉不触发分页
      if (!_this.filterText) {
        if (!firstTag) {
          _this.page.page++;
        }
        let params = {
          limit: _this.page.pageSize,
          offset: (_this.page.page - 1) * _this.page.pageSize
        };
        _this.tenantQuery(params);
      }
    },
    // 筛选方法
    filterVmModel (value) {
      let _this = this;
      _this.filterText = value;
      // 筛选数据，有值时清空选项并按照关键字搜索对应结果集合
      if (value) {
        _this.tenants = [];
        _this.$nextTick(() => {
          _this.page = {
            page: 1,
            pageSize: 15,
            total: 0
          };
          let params = {
            label: _this.filterText,
            limit: _this.page.pageSize,
            offset: (_this.page.page - 1) * _this.page.pageSize
          };
          _this.tenantQuery(params);
        });
      } else {
        // 空值时，触发重置
        this.tenants = [];
        this.$nextTick(() => {
          _this.page = {
            page: 1,
            pageSize: 15,
            total: 0
          };
          let params = {
            limit: _this.page.pageSize,
            offset: (_this.page.page - 1) * _this.page.pageSize
          };
          _this.tenantQuery(params);
        });
      }
    },
    // 请求租户
    tenantQuery (data) {
      let _this = this;
      _this.$http.post({
        url: '/api/sdwan/tenant/getMultiDg',
        data
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          let { objects } = resultBody;
          let arry = [];
          for (let i = 0; i < objects.length; i++) {
            arry.push({
              label: objects[i].userlabel,
              value: objects[i].id
            });
          }
          _this.tenants.push(...arry);
        }
      });
    },
    // 搜索
    search () {
      let _this = this;
      _this.page.page = 1;
      _this.refresh();
    },
    // 重置
    reset () {
      let _this = this;
      _this.page.page = 1;
      _this.filterSearch = {
        userlabel: null
      };
      _this.refresh();
    },
    // 刷新
    refresh () {
      let _this = this;
      let params = {
        userlabel: _this.filterSearch.userlabel,
        limit: _this.page.pageSize,
        offset: (_this.page.page - 1) * _this.page.pageSize
      };
      _this.$http.post({
        url: '/api/sdwan/vpn/query',
        data: params
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          let { count, objects } = resultBody;
          _this.page.total = count;
          _this.dataList = objects;
        }
      });
    },
    // 过滤显示字段
    changeColumn (columns) {
      this.columns = columns;
      this.$refs.table.doLayout();
    },
    // 切换页码 & 显示条数
    changePage (page) {
      if (page.page) {
        this.page.page = page.page;
      } else {
        this.page.page = 1;
        this.page.pageSize = page.limit;
      }
      this.refresh();
    },
    // 显示弹出框
    showDialog (type, row) {
      let _this = this;
      _this.dvEdit = true;
      // _this.popSites();
      if (type === 'add') {
        _this.diagTitle = '新建租户VPN';
        _this.$nextTick(() => {
          _this.$refs['ruleForm'].clearValidate();
        });
        _this.form = {
          dgId: null,
          instanceName: null,
          userlabel: null,
          rd: null,
          description: null,
          siteIdList: []
        };
        _this.siteFlag = true;
      } else {
        _this.diagTitle = '编辑租户VPN';
        _this.$nextTick(() => {
          let siteList = [];
          for (let i = 0; i < row.vpnList.length; i++) {
            siteList.push(row.vpnList[i].siteId);
          }
          _this.form = {
            id: row.id,
            dgId: row.dgId,
            instanceName: row.instanceName,
            userlabel: row.userlabel,
            rd: row.rd,
            description: row.description,
            siteIdList: siteList
          };
          if (siteList.length > 0) {
            _this.siteFlag = true;
            for (let i = 0; i < _this.siteList.length; i++) {
              for (let k = 0; k < row.vpnList.length; k++) {
                if (_this.siteList[i].id === row.vpnList[k] && row.vpnList[i].status) {
                  _this.siteList[i].disabled = true;
                }
              }
            }
          } else {
            _this.siteFlag = true;
          }
        });

      }
    },
    // 提交创建
    onSubmit () {
      let _this = this;
      let params = {
        dgId: _this.form.dgId,
        instanceName: _this.form.instanceName,
        userlabel: _this.form.userlabel,
        rd: _this.form.rd,
        description: _this.form.description,
        siteIdList: _this.form.siteIdList
      };
      let rds = Number(_this.form.rd.substring(0, _this.form.rd.indexOf(":")));
      let rde = Number(_this.form.rd.substring(_this.form.rd.indexOf(":") + 1, _this.form.rd.length));
      _this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          if (rds < 0 || rds > 65535 || rde < 0 || rde > 4294967295) {
            _this.$message.error('RD范围：<0-65535>:<0-4294967295>');
            return false;
          } else {
            if (_this.form.id) {
              params.id = _this.form.id;
            }
            _this.$http.post({
              url: '/api/sdwan/vpn/create',
              data: params
            }).then(res => {
              let { status, resultBody } = res;
              if (status === '0') {
                if (resultBody.length === 0) {
                  _this.$message({
                    message: _this.form.id ? '更新成功！' : '创建成功！',
                    type: 'success'
                  });
                  _this.dvEdit = false;
                  _this.refresh();
                } else {
                  for (let i = 0; i < resultBody.length; i++) {
                    if (!resultBody[i].succ) {
                      _this.$message.error(resultBody[i].info);
                    } else {
                      _this.$message({
                        message: _this.form.id ? '更新成功！' : '创建成功！',
                        type: 'success'
                      });
                      _this.dvEdit = false;
                      _this.refresh();
                    }
                  }
                }
              }
            });
          }
        } else {
          _this.$message.error('请检查必填项！');
          return false;
        }
      });
    },
    // 删除
    handleDelete (scope) {
      let _this = this;
      _this.$confirm('您确定要删除当前数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        _this.$http.deleted({
          url: '/api/sdwan/vpn/',
          data: {
            id: scope.row.id
          }
        }).then(res => {
          let { status } = res;
          if (status === '0') {
            _this.$message.success('删除成功！');
            _this.refresh();
          }
        });
      }).catch(() => {
        _this.$message.info('取消删除');
      });
    }
  }
};
</script>

<style lang='scss' scoped>
.page-content {
  width: 100%;
  height: 100%;

  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
  .table-box {
    ::v-deep .el-button {
      padding: 0;
    }
  }

  ::v-deep .el-dialog__body {
    padding-bottom: 0;
  }
}
</style>